structure of Java Code
Java code is structured in a hierarchical manner, with classes at the top of the hierarchy and methods and variables at the bottom.
Classes are the basic building blocks of Java code. They define the data and behavior of objects. Classes are declared using the class keyword.
Methods are blocks that contains code to perform a specific task. Methods are defined within classes. They can be called by other methods or by objects. Methods are declared using the public keyword, followed by the method name, the return type, and the parameter list.
Variables are used to store data. Variables are declared using the public keyword, followed by the variable name and the data type.
Here is the simple code that shows basic structure of Java
Java Structure
package com.example.myapp;
public class Main{
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Output
Hello, world!
Multiple Classes and Methods
We can have Multiple classes and methods in a code. The methods within another class can be called using
Objects.Let us see an example having multiple class, methods and objects.
Java object structure example
package com.example.myapp;
public class Main{
public static void main(String[] args) {
System.out.println("Hello, world!");
//Create a Person instance with a name
Person person = new Person("Arnold");
//Call the sayHello method of the Person instance
person.sayHello();
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + "!");
}
}
Output
Hello, world!
Hello, my name is Arnold!
In the above example we have a package, a
HelloWorld class which has main method to execute java program. An object is create with a value
Arnold and
the
person.sayHello() calls the
Person class. The name will be stored in a private string name and printed using sayHello.
Note : The above example maybe difficult to understand but no worries, we will discuss about Class,Objects,Package,Import,Private etc in upcoming topics.